<!-- 子组件：UnitInsert.vue -->
<script setup>
import { ref, watch, defineProps, defineEmits } from "vue";
import request from '@/api/request';
import { ElMessage } from 'element-plus';

// 定义事件：传递新增数据给父组件
const emits = defineEmits(["ref-table", "cancel"]);

// 接收父组件传递的初始数据（新增时为空）
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
});

// 表单数据（初始化默认值）
const unitConversion = ref({
  isMainUnit: props.data.isMainUnit ?? '1', // 默认"是"主单位
  conversionRate: props.data.conversionRate ?? 1,
  status: props.data.status ?? '1' // 默认启用
});

// 自动生成功能相关
const autoGenerate = ref(false);

// 存储主单位列表（供非主单位选择）
const mainUnits = ref([]);

// 获取主单位列表
const fetchMainUnits = async () => {
  try {
    const response = await request.get("/unitConversion/index", {
      params: { isMainUnit: 1, size: 100 } // 只查主单位
    });
    mainUnits.value = response.data.records;
  } catch (error) {
    ElMessage.error("获取主单位失败");
  }
};

// 自动生成单位编码
const generateUnitCode = () => {
  const timestamp = new Date().getTime().toString();
  return 'U-' + timestamp.substring(timestamp.length - 6);
};

// 处理自动生成功能开关
const handleAutoGenerate = (val) => {
  if (val) {
    // 开启自动生成
    unitConversion.value.unitId = generateUnitCode();
  } else {
    // 关闭自动生成，清空编码
    unitConversion.value.unitId = '';
  }
};

// 重新生成编码
const regenerateCode = () => {
  if (autoGenerate.value) {
    unitConversion.value.unitId = generateUnitCode();
  }
};

// 监听是否为主单位的变化
watch(
  () => unitConversion.value.isMainUnit,
  (newVal) => {
    if (newVal === '1') {
      // 主单位强制转换率为1，清空主单位选择
      unitConversion.value.conversionRate = 1;
      unitConversion.value.mainUnit = '';
    } else {
      // 非主单位加载主单位列表
      fetchMainUnits();
    }
  },
  { immediate: true }
);

// 提交表单
const onSubmit = () => {
  // 前端基础校验
  if (!unitConversion.value.unitId) {
    return ElMessage.warning("请输入单位编码");
  }
  if (!unitConversion.value.unitName) {
    return ElMessage.warning("请输入单位名称");
  }
  if (unitConversion.value.isMainUnit === '2' && !unitConversion.value.mainUnit) {
    return ElMessage.warning("请选择主单位");
  }
  
  // 调用后端新增接口
  request({
    url: '/unitConversion/insert',
    method: 'post',
    data: {
      ...unitConversion.value,
      // 转换字段名适配后端（后端用baseUnitId，前端绑定mainUnit）
      baseUnitId: unitConversion.value.mainUnit,
      // 转换字符串为数字（后端接收Number类型）
      isMainUnit: Number(unitConversion.value.isMainUnit),
      status: Number(unitConversion.value.status),
      conversionRate: Number(unitConversion.value.conversionRate)
    }
  }).then(res => {
    emits("ref-table")
     if (res.code !== 200) {
      ElMessage.error(res.message || res.data)
    } else{
      ElMessage.success('添加成功')
    }
    // 重置自动生成功能
    if (autoGenerate.value) {
      unitConversion.value.unitId = generateUnitCode();
    }
  })
};
</script>

<template>
  <div>
    <el-form 
      :model="unitConversion" 
      label-width="80px" 
      size="normal" 
      class="form-container"
    >
      <el-form-item label="单位编码" required>
        <div style="display: flex; align-items: center; width: 800px;">
          <el-input 
            v-model="unitConversion.unitId" 
            placeholder="请输入单位编码" 
            style="flex: 1;"
            :readonly="autoGenerate"
          ></el-input>
          <el-switch 
            v-model="autoGenerate"
            active-text="自动生成"
            @change="handleAutoGenerate"
            style="margin-left: 15px;"
          />
          <el-button 
            v-if="autoGenerate"
            @click="regenerateCode"
            style="margin-left: 10px;"
            size="small"
          >
            重新生成
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="单位名称" required>
        <el-input 
          v-model="unitConversion.unitName" 
          placeholder="请输入单位名称" 
          style="width: 800px;"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="是否为主单位" required>
        <el-radio-group v-model="unitConversion.isMainUnit">
          <el-radio value="1">是</el-radio>
          <el-radio value="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item 
        v-if="unitConversion.isMainUnit === '2'" 
        label="换算比例" 
        required
      >
        <el-input-number 
          v-model="unitConversion.conversionRate" 
          :min="1" 
          step="1" 
          placeholder="请输入换算比例"
        ></el-input-number>
      </el-form-item>
      
      <el-form-item 
        v-if="unitConversion.isMainUnit === '2'" 
        label="主单位" 
        required
      >
        <el-select 
          v-model="unitConversion.mainUnit" 
          placeholder="请选择主单位" 
          style="width: 300px;"
          clearable
          popper-append-to-body
        >
          <el-option 
            v-for="(unit, index) in mainUnits" 
            :key="index + '-' + unit.unitId"
            :value="unit.unitId" 
            :label="unit.unitName"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="是否启用" required>
        <el-radio-group v-model="unitConversion.status">
          <el-radio value="1">是</el-radio>
          <el-radio value="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input 
          v-model="unitConversion.SpecificationsAndModels" 
          placeholder="请输入备注" 
          type="textarea"
          style="width: 800px; height: 100px;"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定新增</el-button>
       
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.form-container {
  padding: 20px;
}
</style>